//
//  YWAssignDetectAndUpkeepTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/6.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWAssignDetectAndUpkeepTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "NSDate+Additions.h"
#import "MBProgressHUD.h"
#import "YWLoginTool.h"

#import "YWTextFieldCell.h"
#import "YWWriteNoteCell.h"
#import "YWEquipmentAndGreenPointTableViewCell.h"

#import "YWContactManager.h"
#import "YWHandler.h"
#import "YWEquipmentType.h"
#import "YWEquipmentManager.h"
#import "YWMission.h"
#import "YWEquipment.h"

#import "YWSelectContactTableViewController.h"
#import "YWSelectInspectLineEquipmentTableViewController.h"
#import "YWSelectEquipmentSystemTableViewController.h"
#import "YWDetectAndUpkeepManager.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWSelectBuildingTableViewController.h"
#import "YWSelectMissionCycleTableViewController.h"

static CGFloat const kDatePickerViewH = 216;
static NSInteger const loadingStatusIsDefault = 0;
static NSInteger const loadingStatusIsLoading = 1;
static NSInteger const loadingStatusFail = -1;

@interface YWAssignDetectAndUpkeepTableViewController ()<YWTextFieldCellDelegate,YWWriteNoteCellDelegate,YWContactVCSelectContactDelegate,YWSelectBuildingTableViewControllerDelegate,YWSelectMissionCycleDelegate,YWSelectInspectLineEquipmentTableVCDelegate>{
    YWBuilding *currentBuilding;
    YWEquipmentType *currentEquipmentType;
    YWAssignMissionCount *currentAssignMissionCount;
    YWMissionCycle currentMissionCycle;
    NSInteger loadingStatus;//0默认,1 查询中,-1失败
    NSInteger assignQuantity;
    NSString *startDate;
    NSString *endDate;
    NSString *missionNote;
    BOOL isShowDatePicker;
    BOOL isStartDate;
}
@property (nonatomic, strong) NSArray *allBuildings;
@property (nonatomic, strong) NSMutableArray *selectEquipmentArray;
@property (nonatomic, strong) NSMutableArray *executors;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) NSDateFormatter* dateFormatter;
@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWAssignDetectAndUpkeepTableViewController
- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"assignMission", nil);//@"分配任务";
    //键盘弹起的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", nil) style:UIBarButtonItemStylePlain target:self action:@selector(clickCancelBarButtonEvent:)];
    
    [self setupData];
    [self setupTableView];
}

- (void)setupData{
    currentMissionCycle = YWMissionCycleNull;
    currentBuilding = self.allBuildings.count>0?self.allBuildings[0]:nil;
    
    NSDateFormatter *formatter = [self dateFormatter];
    NSString *string = [formatter stringFromDate:[NSDate date]];
    startDate = string;
}

- (NSDateFormatter*)dateFormatter
{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return _dateFormatter;
}

- (void)setupTableView{
    [self.tableView registerClass:[YWTextFieldCell class] forCellReuseIdentifier:YWTextFieldCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWEquipmentAndGreenPointTableViewCell class] forCellReuseIdentifier:YWEquipmentAndGreenPointTableViewCellIdentifier];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
    [self.datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, kDatePickerViewH)];
}

- (NSArray *)allBuildings{
    if (!_allBuildings) {
        _allBuildings = [[YWBuildingManager shareManager] allBuilding];
    }
    return _allBuildings;
}

- (NSMutableArray *)executors{
    if (!_executors) {
        _executors = [NSMutableArray array];
    }
    return _executors;
}

- (NSMutableArray *)selectEquipmentArray{
    if (!_selectEquipmentArray) {
        _selectEquipmentArray = [NSMutableArray array];
    }
    return _selectEquipmentArray;
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 7) {
        return 90;
    }else if (indexPath.section == 3){
        if (indexPath.row == 0) {
            return 44;
        }else{
            return 60;
        }
    }else{
        return 44;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 8;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 5) {
        return self.executors.count > 0 ? self.executors.count : 1;
    }else if (section ==6){
        return 2;
    }else if (section == 3){
        return self.selectEquipmentArray.count>0 ? self.selectEquipmentArray.count + 1 : 1;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        if (!currentAssignMissionCount) {
            static NSString *cellIdentifier = @"YWAssignCountReuseCellIdentifier";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
                cell.textLabel.font = kContentFont;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            cell.accessoryView = nil;
            cell.textLabel.textColor = [UIColor lightGrayColor];
            if (loadingStatus == loadingStatusIsLoading) {
                cell.textLabel.text = NSLocalizedString(@"isRequiringTheCountOfMaintenance", nil);//@"正在查询当月计划维保数量...";
                UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 17, 17)];
                indicator.color = [UIColor customTextGrayColor];
                cell.accessoryView = indicator;
                [indicator startAnimating];
            }else if (loadingStatus == loadingStatusFail){
                cell.textLabel.text = NSLocalizedString(@"queryFailedAndClickRetry", nil);//@"查询失败,点击重试";
                cell.textLabel.textColor = [UIColor customRedColor];
            }else{
                cell.textLabel.text = currentBuilding == nil ? NSLocalizedString(@"pleaseSelectBuildingAndEquipmentType", nil) : NSLocalizedString(@"pleaseSelectEquipmentTypeFirst", nil);
            }
            return cell;
        }else{
            YWTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTextFieldCellIdentifier];
            cell.tag = 1999;
            cell.delegate = self;
            NSString *typeName = _maintenanceType == YWMaintenanceTypeDetection ? NSLocalizedString(@"detection", nil):NSLocalizedString(@"upkeep", nil);
            
            if (self.selectEquipmentArray.count>0) {
                cell.textFieldContent = nil;
                cell.textFieldPlaceholder = NSLocalizedString(@"cannotWriteTheNumberAfterSelectEquipment", nil);//@"您已选择设备，不可再填写数量";
                cell.canInput = NO;
            }else{
               cell.textFieldPlaceholder = [NSString stringWithFormat:@"%@:%ld 已%@:%ld",NSLocalizedString(@"equipmentCount", nil),(long)currentAssignMissionCount.equipmentTypeQuantity,typeName,(long)currentAssignMissionCount.finishQuantity];
                cell.canInput = YES;
            }
            cell.textFieldKeyboardType = UIKeyboardTypeNumberPad;
            return cell;
        }
    }else if (indexPath.section == 7){
        YWWriteNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.delegate = self;
        return cell;
    }else{
        static NSString *cellIdentifier = @"YWAssignDetectAndUpkeepVCReuseCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.font = kContentFont;
        }
        cell.textLabel.textColor = [UIColor blackColor];
        if (indexPath.section == 0) {
            cell.textLabel.text = currentBuilding ? currentBuilding.buildingName?:NSLocalizedString(@"unknowBuilding", nil) : NSLocalizedString(@"pleaseSelectBuilding", nil);
        }else if (indexPath.section == 1) {
            cell.textLabel.text = currentEquipmentType ? currentEquipmentType.equipmentTypeName?:NSLocalizedString(@"unknowType", nil) : NSLocalizedString(@"pleaseSelectEquipmentType", nil);
            
        }else if (indexPath.section == 3){
            if (indexPath.row==0) {
                cell.textLabel.text = currentEquipmentType ? NSLocalizedString(@"pleaseSelectEquipment", nil): NSLocalizedString(@"pleaseSelectEquipmentTypeFirst", nil);
                cell.textLabel.textColor = currentEquipmentType ? [UIColor blackColor]: [UIColor customTextGrayColor];
                cell.accessoryType = currentEquipmentType ?UITableViewCellAccessoryDisclosureIndicator :UITableViewCellAccessoryNone;
                cell.detailTextLabel.text = nil;
                return cell;
            }else{
                YWEquipmentAndGreenPointTableViewCell* equipmentAndGreenPointcell = [tableView dequeueReusableCellWithIdentifier:YWEquipmentAndGreenPointTableViewCellIdentifier];
                YWEquipment *equipment = self.selectEquipmentArray[indexPath.row-1];
                equipmentAndGreenPointcell.equitmentName = equipment.equipmentName?:@"";
                equipmentAndGreenPointcell.locationString = [[YWBuildingManager shareManager] equipmentLocationNobuilding:equipment]?:[NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"location", nil),NSLocalizedString(@"none", nil)];
                return equipmentAndGreenPointcell;
            }
        }else if (indexPath.section == 4){
            cell.textLabel.text = [YWDetectAndUpkeepManager missionCycleStringWithCycle:currentMissionCycle];
        }else if (indexPath.section == 5){
            if (self.executors.count>0) {
                YWHandler *handler = self.executors[indexPath.row];
                cell.textLabel.text = handler.userName?:@"";
            }else{
                cell.textLabel.text = NSLocalizedString(@"pleaseSelectExecutor", nil);//@"请选择执行人";
            }
        }else if (indexPath.section == 6){
            cell.textLabel.text = indexPath.row==0 ? [NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"startDate", nil),startDate?:NSLocalizedString(@"pleaseSelect", nil)]:[NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"endDate", nil),endDate?:NSLocalizedString(@"pleaseSelect", nil)];
        }
        return cell;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 3) {
        return [self.selectEquipmentArray count]>0 && indexPath.row>0 ? UITableViewCellEditingStyleDelete : UITableViewCellEditingStyleNone;
    }else if (indexPath.section == 5) {
        return [self.executors count]>0 ? UITableViewCellEditingStyleDelete : UITableViewCellEditingStyleNone;
    }else{
        return UITableViewCellEditingStyleNone;
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 3 && [self.selectEquipmentArray count]>0) {
        [self.selectEquipmentArray removeObjectAtIndex:indexPath.row-1];
        if (self.selectEquipmentArray.count==0) {
            [tableView reloadData];
        }else{
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }
    if (indexPath.section == 5 && [self.executors count]>0) {
        [self.executors removeObjectAtIndex:indexPath.row];
        if (self.executors.count==0) {
            [tableView reloadData];
        }else{
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWAssignDetectAndUpKeepTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        NSString *buildingShowName = [YWLoginTool buildingShowName];
        return buildingShowName.length?buildingShowName:NSLocalizedString(@"building", nil);
    }else if (section == 1) {
        return NSLocalizedString(@"equipmentType", nil);//@"设备类型";
    }else if (section==2){
        NSString *maintenTypeName = _maintenanceType == YWMaintenanceTypeDetection ? NSLocalizedString(@"detection", nil):NSLocalizedString(@"upkeep", nil);
        return [NSString stringWithFormat:@"%@%@",maintenTypeName,NSLocalizedString(@"number", nil)];
    }else if (section == 3){
        return NSLocalizedString(@"selectEquipment", nil);//@"选择设备";
    }else if (section == 4){
        return NSLocalizedString(@"missionCycle", nil);//@"循环周期";
    }else if (section==5){
        return NSLocalizedString(@"executor", nil);//@"执行人";
    }else if (section==6){
        return NSLocalizedString(@"startAndEndDate", nil);//@"起止日期";
    }else if (section==7){
        return NSLocalizedString(@"note", nil);//@"备注";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    if (indexPath.section == 0) {
        YWSelectBuildingTableViewController *selectBuildingVC = [[YWSelectBuildingTableViewController alloc] init];
        selectBuildingVC.delegate = self;
        selectBuildingVC.ownBuilding = currentBuilding;
        [self.navigationController pushViewController:selectBuildingVC animated:YES];
    }else if (indexPath.section == 1) {
        YWSelectEquipmentSystemTableViewController *selectEquipmentSystemTypeVC = [[YWSelectEquipmentSystemTableViewController alloc] init];
        selectEquipmentSystemTypeVC.assignMissionTableVC = self;
        [self.navigationController pushViewController:selectEquipmentSystemTypeVC animated:YES];
    }else if (indexPath.section == 2){
        if (currentAssignMissionCount == nil) {
            [self requestAssignMissionCount];
        }
    }else if (indexPath.section == 3){
        if (indexPath.row==0 && currentEquipmentType) {
            YWSelectInspectLineEquipmentTableViewController *selectEquipmentVC = [[YWSelectInspectLineEquipmentTableViewController alloc] init];
            selectEquipmentVC.delegate = self;
            selectEquipmentVC.buildingId = currentBuilding.buildingId;
            selectEquipmentVC.ownEquipmentArray = self.selectEquipmentArray;
            //把当前的设备类型传过去，直接定位到设备类型下的设备
            selectEquipmentVC.equipmentTypeId = currentEquipmentType.equipmentTypeId;
            [self.navigationController pushViewController:selectEquipmentVC animated:YES];
        }else{
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
        }
    }else if (indexPath.section ==4){
        YWSelectMissionCycleTableViewController *selectCycleVC = [[YWSelectMissionCycleTableViewController alloc] init];
        selectCycleVC.missionCycle = currentMissionCycle;
        selectCycleVC.delegate = self;
        [self.navigationController pushViewController:selectCycleVC animated:YES];
    }
    else if (indexPath.section == 5){
        if (currentBuilding.buildingId.length) {
            YWSelectContactTableViewController *selectContactVC = [[YWSelectContactTableViewController alloc] init];
            selectContactVC.delegate = self;
            selectContactVC.buildingId = currentBuilding.buildingId;
            selectContactVC.isMultiSelect = YES;
            selectContactVC.ownContacts = self.executors;
            selectContactVC.titleName = NSLocalizedString(@"selectExecutor", nil);//@"选择执行人";
            [self.navigationController pushViewController:selectContactVC animated:YES];
        }else{
            NSString *buildingShowName = [YWLoginTool buildingShowName];
            [YWCommonTool showTextHUDWithContent:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"firstSelect", nil),buildingShowName]];
        }
        
    }else if (indexPath.section == 6){
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        isStartDate = indexPath.row == 0 ? YES : NO;
        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height -self.tableView.bounds.size.height) animated:YES];
        isShowDatePicker = YES;
        [UIView animateWithDuration:0.25 animations:^{
            self.datePicker.frame=CGRectMake(0, SCREEN_HEIGHT-216, SCREEN_WIDTH, 216);
        }];
    }
}
#pragma mark - YWSelectBuildingTableViewControllerDelegate
-(void)popSelectedBuilding:(YWBuilding *)building{
    if (building && ![currentBuilding.buildingId isEqualToString:building.buildingId]) {
        currentBuilding = building;
        
        currentEquipmentType = nil;
        currentAssignMissionCount = nil;
        loadingStatus = loadingStatusIsDefault;
        
        YWTextFieldCell *cell = nil;
        cell = [self.tableView viewWithTag:1999];
        if (cell == nil) {
            cell = [self.tableView dequeueReusableCellWithIdentifier:YWTextFieldCellIdentifier];
        }
        cell.textFieldContent = nil;
        
        [self.selectEquipmentArray removeAllObjects];
        
        [self.tableView reloadData];
        [self requestAssignMissionCount];
    }
}

#pragma mark - YWSelectEquipmentTypeTableViewControllerDelegate
- (void)popSelectedEquipmentType:(YWEquipmentType *)equipmentType{
    if (equipmentType && currentEquipmentType.equipmentTypeId!=equipmentType.equipmentTypeId) {
        currentEquipmentType = equipmentType;
        
        currentAssignMissionCount = nil;
        loadingStatus = loadingStatusIsDefault;
        
        YWTextFieldCell *cell = nil;
        cell = [self.tableView viewWithTag:1999];
        if (cell == nil) {
            cell = [self.tableView dequeueReusableCellWithIdentifier:YWTextFieldCellIdentifier];
        }
        cell.textFieldContent = nil;
        
        [self.tableView reloadData];
        [self requestAssignMissionCount];
    }
}

#pragma mark - YWContactVCSelectContactDelegate
- (void)selectMultipleContact:(NSArray *)contactArray{
//    NSArray* array = [[NSArray alloc] initWithArray:contactArray];
//    self.executors = array;
    [self.executors removeAllObjects];
    [self.executors addObjectsFromArray:contactArray];
    [self.tableView reloadData];
}

#pragma mark - YWTextFieldCellDelegate
- (void)passTextFieldContent:(NSString *)content cell:(UITableViewCell *)cell{
    //任务数量、即是检测设备总数
    assignQuantity = [content integerValue];
}

#pragma mark - YWWriteNoteCellDelegate
- (void)passNote:(NSString *)note{
    missionNote = note;
}

#pragma mark - YWSelectInspectLineEquipmentTableVCDelegate
- (void)selectInspectEquipments:(NSArray *)equipmentArray{
    [self.selectEquipmentArray removeAllObjects];
    [self.selectEquipmentArray addObjectsFromArray:equipmentArray];
    assignQuantity = self.selectEquipmentArray.count;
    [self.tableView reloadData];
}

#pragma mark - YWSelectMissionCycleDelegate
- (void)selectMissionCycle:(NSInteger)missionCycle{
    currentMissionCycle = missionCycle;
    [self.tableView reloadData];
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 4.0;
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:NSLocalizedString(@"send", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickSenderButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
    }
    return _footView;
}

-(UIDatePicker *)datePicker{
    if (!_datePicker) {
        _datePicker=[[UIDatePicker alloc]init];
        [_datePicker setBackgroundColor:[UIColor whiteColor]];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        _datePicker.locale =[NSLocale localeWithLocaleIdentifier:@"zh"];
        [_datePicker setMinimumDate:[NSDate date]];
        [_datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
        [self.navigationController.view addSubview:_datePicker];
    }
    return _datePicker;
}
-(void)dateChanged:(id)sender{
    UIDatePicker *picker = (UIDatePicker*)sender;
    NSDate *date = picker.date;
    NSDateFormatter *formatter = [self dateFormatter];
    NSString *string = [formatter stringFromDate:date];
    if (isStartDate) {
        startDate = string;
    }else{
        endDate = string;
    }
    [self.tableView reloadData];
}
-(void)resetDatePicker{
    isShowDatePicker = NO;
    [UIView animateWithDuration:0.25 animations:^{
        [_datePicker setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, kDatePickerViewH)];
    }];
}

#pragma mark - UIKeyboardNSNotification
- (void)keyboardWillShow:(NSNotification*)notification
{
    [self resetDatePicker];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
    if (isShowDatePicker) {
        [self resetDatePicker];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self resetDatePicker];
}

- (void)requestAssignMissionCount{
    if (currentBuilding && currentEquipmentType) {
        currentAssignMissionCount = nil;
        loadingStatus = loadingStatusIsLoading;
        [self.tableView reloadData];
        [YWDetectAndUpkeepManager requestAssignMissionCountWithBuildingId:currentBuilding.buildingId equipmentTypeId:currentEquipmentType.equipmentTypeId maintenanceTypeId:self.maintenanceType WithComplete:^(YWAssignMissionCount *assignMissionCount) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (assignMissionCount) {
                    currentAssignMissionCount = assignMissionCount;
                    currentMissionCycle = currentAssignMissionCount.maintenanceCycle;
                    loadingStatus = 0;
                }else{
                    loadingStatus = loadingStatusFail;
                }
                [self.tableView reloadData];
            });
        }];
    }
}

- (void)clickSenderButtonEvent:(id)sender{
    [self resetDatePicker];
    if (currentEquipmentType == nil) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSelectEquipmentType", nil)];
        return;
    }
    if (currentAssignMissionCount.equipmentTypeQuantity == 0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"cannotAssignBecauseOfNoEquipment", nil)];
        return;
    }
    if (assignQuantity==0 && self.selectEquipmentArray.count == 0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseInputTheNumberOrEquipment", nil)];
        return;
    }
    if (assignQuantity > currentAssignMissionCount.equipmentTypeQuantity) {//(currentAssignMissionCount.equipmentTypeQuantity - currentAssignMissionCount.finishQuantity)
        NSString *maintenTypeName = _maintenanceType == YWMaintenanceTypeDetection ? NSLocalizedString(@"detection", nil):NSLocalizedString(@"upkeep", nil);
        NSString *tips = [NSString stringWithFormat:@"%@%@",maintenTypeName,NSLocalizedString(@"numberMustLessThanEquipmentCount", nil)];
        [YWCommonTool showTextHUDWithContent:tips];
        return;
    }
    if (self.executors.count==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSelectExecutor", nil)];
        return;
    }
    if (startDate.length==0 || endDate.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSlectStartAndEndDate", nil)];
        return;
    }
    if ([[startDate stringByReplacingOccurrencesOfString:@"-" withString:@""] integerValue]>[[endDate stringByReplacingOccurrencesOfString:@"-" withString:@""] integerValue]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"startDateMustLessThanEndDate", nil)];
        return;
    }
    if (missionNote.length>100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:missionNote]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    //点击发送
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makeSureToAssignMission", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        [self assignDetectAndUpKeepMission];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)assignDetectAndUpKeepMission{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSMutableString *executorIds = [[NSMutableString alloc] init];
    [self.executors enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx!=0) {
            [executorIds appendString:@","];
        }
        [executorIds appendString:[NSString stringWithFormat:@"%ld",(long)handler.uniqueId]];
    }];
    [params setValue:executorIds forKey:@"executorIds"];
    [params setValue:currentBuilding.buildingId?:@"" forKey:@"building.buildingId"];
    [params setValue:startDate?:@"" forKey:@"startTime"];
    [params setValue:endDate?:@"" forKey:@"cutoffTime"];
    [params setValue:missionNote?:@"" forKey:@"note"];
    [params setValue:@(self.maintenanceType) forKey:@"maintenanceTypeId"];
    [params setValue:@(currentEquipmentType.equipmentTypeId) forKey:@"equipmentType.equipmentTypeId"];
    [params setValue:currentEquipmentType.equipmentTypeName?:@"" forKey:@"equipmentType.equipmentTypeName"];
    //可选设备
    if (self.selectEquipmentArray.count>0) {
        NSMutableString * equipmentIds = [[NSMutableString alloc] init];
        [self.selectEquipmentArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx!=0) {
                [equipmentIds appendString:@","];
            }
            [equipmentIds appendString:equipment.equipmentId];
        }];
        [params setValue:equipmentIds forKey:@"equipmentIds"];
    }
    [params setValue:@(assignQuantity) forKey:@"missionQuantity"];
    [params setValue:@(currentAssignMissionCount.equipmentTypeQuantity) forKey:@"equipmentTotal"];
    //[params setValue:@(currentAssignMissionCount.maintenanceCycle) forKey:@"maintenanceCycle"];
    [params setValue:@(currentMissionCycle) forKey:@"missionCycle"];
    [params setValue:@([NSDate date].year) forKey:@"theYear"];
    [params setValue:@([NSDate date].month) forKey:@"theMonth"];
    YWLog(@"%@",params);
    [YWDetectAndUpkeepManager assiginDetectAndUpkeepMission:params WithComplete:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextAssignSuccess, nil)];
            [self.navigationController popViewControllerAnimated:YES];
            //currentAssignMissionCount = nil;
            //currentEquipmentType = nil;
            //[self.tableView reloadData];
        }
    }];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)clickCancelBarButtonEvent:(id)sender{
    if (currentEquipmentType || assignQuantity>0  ||self.executors.count>0 || missionNote.length>0 || self.selectEquipmentArray>0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"quitEditing", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
